package com.ruoyi.common.core.utils;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@ApiModel("远程请求处理工具类")
@Component
@Data
public class RestTemplateUtils {

    public static <T> ResponseEntity<T> get(String url, Class tClass) {
        RestTemplate restTemplate = init();
        ResponseEntity<T> forEntity = restTemplate.getForEntity(url, tClass);
        return forEntity;
    }

    public static <T> ResponseEntity<T> post(String url, Class tClass, MultiValueMap<String, String> map) {
        RestTemplate restTemplate = init();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, httpHeaders);
        ResponseEntity<T> openLinkEntityResponseEntity = restTemplate.postForEntity(url, httpEntity, tClass);
        return openLinkEntityResponseEntity;
    }

    public static <T> ResponseEntity<T> post(String url, Class tClass, JSONObject map) {
        RestTemplate restTemplate = init();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<T> openLinkEntityResponseEntity = restTemplate.postForEntity(url, httpEntity, tClass);
        return openLinkEntityResponseEntity;
    }

    public static <T> ResponseEntity<String> execute(String url, Class tClass, HttpHeaders headers) {
        RestTemplate restTemplate = init();
        HttpEntity httpEntity = new HttpEntity<>(headers);
        ResponseEntity<String> forEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, tClass);
        return forEntity;
    }


    public static RestTemplate init() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("utf-8")));
        return restTemplate;
    }

}
